<template>
  <!-- 年票季票下单 -->
  <view v-if="contentDisplay" class="content">
    <!-- 日历 -->
    <littleCalendar
      v-if="productTicket.ubr_product_category === 'SINGLE'"
      :week-day-list="WeekDayList"
      :date-list="dateList"
      :datetime="datetime"
      :price="productTicket.price"
      :show="dayListshow"
      @changeDatetime="changeDatetime"
      @close="dayListClose"
      @eject="eject"
      @changeDateBig="changeDateBig"
      @showLargeCalendar="showLargeCalendar"
    />
    <!-- 主体卡片区域 -->
    <view :class="devtools==='ios'?'content-card-fa-ios':'content-card-fa'">
      <view class="content-card">
        <!-- 商品名称 -->
        <view class="card-commodity-name">{{ productTicket.name }}</view>
        <!-- 购买数量 -->
        <view class="card-purchase-quantity">
          <view class="card-purchase-quantity-left">购买数量</view>
          <view class="card-purchase-quantity-right">
            <view class="card-purchase-quantity-right-reduce" @click="rectangle">
              <i class="reduce-rectangle" />
            </view>
            <view class="card-purchase-quantity-right-number">
              <input type="number" :value="number" @focus="getNumber" @blur="verification">
            </view>
            <view class="card-purchase-quantity-right-add" @click="add">
              <i class="reduce-rectangle" />
              <i class="reduce-rectangle-rotate" />
            </view>
          </view>
        </view>
        <!-- 输入款区域 -->
        <inputBox
          :input-box-list="inputBoxList"
          @choice-passenger="choicePassenger"
          @changeLanguage="changeLanguage"
          @changeInput="changeInput"
          @changeID="changeID"
        />
      </view>
    </view>
    <!-- 支付按钮 -->
    <payment :price="productTicket.price" :number="number" @ticketOrder="ticketOrder" />
    <!-- 弹出框 -->
    <choicePopup
      :show="show"
      :query="query"
      @close="close"
      @updataId="updataId"
      @updataTraveler="updataTraveler"
    />
  </view>
</template>

<script>
import inputBox from '@com/order/inputBox'
import payment from '@com/order/payment'
import { getProductTicket, getStockTicket } from '@api/poduct'
import { showToast, getNowFormatDate, getNextYear } from '@utils/myApproach'
import { get } from '@utils/storage'
import { ticketOrder } from '@api/order'
import choicePopup from '@com/order/choicePopup'
import littleCalendar from '@com/order/littleCalendar'
export default {
  onLoad(option) {
    this.uid = option.uid
    this.getProductTicket()
    console.log(getNowFormatDate(), getNextYear())
  },
  components: {
    inputBox,
    payment,
    choicePopup,
    littleCalendar
  },
  data() {
    return {
      uid: null,
      productTicket: null,
      number: null,
      old: {
        number: 0
      },
      minNumber: null,
      maxNumber: null,
      setNumber: null,
      baseNumber: null,
      baseArray: [],
      inputBoxList: [],
      passengerList: [],
      ubr_product_code_number_list: [],
      show: false,
      dayListshow: false,
      WeekDayList: null,
      contentDisplay: false,
      datetime: null,
      dateList: null,
      // 表示得到焦点和失去焦点，0表示失去
      judge: 0,
      query: {
        type: 'traveler',
        id_type: '',
        index: null,
        code: null,
        personType: null
      }
    }
  },
  computed: {
    init() {
      return get('init')
    },
    devtools() {
      return get('devtools')
    }
  },
  watch: {
    // detailValue(data) {
    // }
  },
  methods: {
    getProductTicket() {
      getProductTicket(this.uid).then((res) => {
        this.productTicket = res.data.data
        this.number = 1
        this.baseNumber = 0
        this.productTicket.ubr_product.forEach((item) => {
          this.baseNumber = parseInt(this.baseNumber) + parseInt(item.number)
          this.ubr_product_code_number_list.push(parseInt(item.number))
          for (var j = 0; j < item.number; j++) {
            const baseArrayItem = {
              code: item.code,
              personType: item.person_type
            }
            this.baseArray.push(baseArrayItem)
          }
        })
        console.log('baseArray', this.baseNumber)
        this.minNumber = this.baseNumber
        this.maxNumber = this.init.query.ticket_max_number
        for (var i = 0; i < this.minNumber; i++) {
          // console.log(i)
          const inputBoxListItem = {
            id_no: '',
            telephone: '',
            first_name: '',
            last_name: '',
            language: 'EN',
            id_type: 'GovernmentId',
            personType: this.baseArray[i].personType,
            code: this.baseArray[i].code,
            baseNumber: this.baseNumber
          }
          this.inputBoxList.push(inputBoxListItem)
        }

        if (this.productTicket.ubr_product_category === 'SINGLE') {
          this.WeekDayList = this.getWeekDay()
          const dateObj = {
            start_at: getNowFormatDate(),
            end_at: getNextYear()
          }
          getStockTicket(this.uid, dateObj).then((res) => {
            this.dateList = res.data.data
            this.WeekDayList.forEach((item, index, array) => {
              res.data.data.forEach(value => {
                value = value.slice(0, 10)
                if (value === item.date) {
                  array[index].ticketBeing = true
                  return
                }
              })
              array[index].year = item.date.slice(0, 4)
              array[index].date = item.date.slice(5, 7) + '/' + item.date.slice(8, 10)
              this.contentDisplay = true
            })
          })
        } else {
          this.datetime = null
          this.contentDisplay = true
        }
      })
    },
    // 减少数量
    rectangle() {
      if (this.number * this.baseNumber > this.minNumber) {
        this.number = this.number - 1
        for (var i = 0; i < this.baseNumber; i++) {
          this.inputBoxList.pop()
        }
      } else {
        showToast('购买的门票数量最小不可低于' + this.minNumber + '张')
      }
    },
    // 增加数量
    add() {
      var time = 0
      if (this.judge === 1) {
        time = 100
      }
      setTimeout(() => {
        if ((this.number + 1) * this.baseNumber < this.maxNumber) {
          for (var i = 0; i < this.baseNumber; i++) {
            const inputBoxListItem = {
              id_no: '',
              telephone: '',
              first_name: '',
              last_name: '',
              language: 'EN',
              id_type: 'GovernmentId',
              personType: this.baseArray[i].personType,
              code: this.baseArray[i].code,
              baseNumber: this.baseNumber
            }
            this.inputBoxList.push(inputBoxListItem)
            this.$forceUpdate()
          }
          this.number = this.number + 1
        } else {
          showToast('购买的门票数量不可超过 ' + this.maxNumber + '张')
        }
      }, time)
    },
    // 获得改变前number
    getNumber() {
      this.setNumber = this.number
      this.number = ''
      this.judge = 1
    },
    // 直接输入数量验证
    verification(e) {
      this.judge = 0
      const data = parseInt(e.detail.value)
      if (String(data) === 'NaN') {
        this.number = this.setNumber
        showToast('请输入数字')
      } else {
        if (data * this.baseNumber < this.minNumber) {
          this.number = this.setNumber
          showToast('购买的门票数量最小不可低于' + this.minNumber + '张')
        } else if (data * this.baseNumber > this.maxNumber) {
          this.number = this.setNumber
          showToast('购买的门票数量不可超过 ' + this.maxNumber + '张')
        } else {
          this.number = data
          const length = this.inputBoxList.length
          if (length < this.number * this.baseNumber) {
            for (var i = length; i < this.number * this.baseNumber; i++) {
              const inputBoxListItem = {
                id_no: '',
                telephone: '',
                first_name: '',
                last_name: '',
                language: 'EN',
                id_type: 'GovernmentId',
                personType: this.baseArray[i - length].personType,
                code: this.baseArray[i - length].code,
                baseNumber: this.baseNumber
              }
              this.inputBoxList.push(inputBoxListItem)
            }
          } else if (length > this.number * this.baseNumber) {
            for (var j = length; j > this.number * this.baseNumber; j--) {
              this.inputBoxList.pop()
            }
          }
        }
      }
    },
    // 切换语言
    changeLanguage(index) {
      this.inputBoxList[index].language =
        this.inputBoxList[index].language === 'EN' ? 'CN' : 'EN'
      this.inputBoxList[index].first_name = ''
      this.inputBoxList[index].last_name = ''
      this.$forceUpdate()
      console.log(this.inputBoxList[index])
    },
    // 同步input
    changeInput(e) {
      const model = e.currentTarget.dataset.model
      const index = e.currentTarget.dataset.index
      this.inputBoxList[index][model] = e.detail.value
      this.$forceUpdate()
    },
    // 切换证件类型
    changeID(index) {
      this.show = true
      this.query.type = 'ID'
      this.query.id_type = this.inputBoxList[index].id_type
      this.query.index = index
    },
    updataId(data) {
      this.inputBoxList[data.index].id_type = data.value
    },
    // 选择常用旅客
    choicePassenger(index) {
      this.show = true
      this.query.type = 'traveler'
      this.query.index = index
      this.query.code = this.inputBoxList[index].code
      this.query.personType = this.inputBoxList[index].personType
      this.query.baseNumber = this.baseNumber
    },
    updataTraveler(data) {
      data.item.id_type = data.item.id_type_display
      data.item.language = data.item.name_type_display === 'CN' ? 'EN' : 'CN'
      data.item.code = data.code
      data.item.personType = data.personType
      data.item.baseNumber = data.baseNumber
      if (data.item.language === 'EN') {
        data.item.first_name = data.item.full_name
      }
      console.log('data', data)
      this.inputBoxList[data.index] = data.item
      this.$forceUpdate()
    },
    close() {
      this.show = false
    },
    dayListClose() {
      this.dayListshow = false
    },
    eject() {
      this.dayListshow = true
    },
    // 选择日期
    changeDatetime(data) {
      this.datetime =
        data.year + '-' + data.date.slice(0, 2) + '-' + data.date.slice(3, 5)
      // + 'T00:00:00'
    },
    changeDateBig(data) {
      this.datetime = data
    },
    // 前往支付
    ticketOrder() {
      if (this.productTicket.ubr_product_category === 'SINGLE') {
        if (this.datetime === null) {
          showToast('请选择出行日期')
          return
        } else {
          this.datetime = this.datetime + 'T00:00:00'
        }
      } else {
        this.datetime = null
      }
      const query = {
        product: this.productTicket.uid,
        number: this.number,
        ticketEntity: [],
        contact: {
          name_type: this.inputBoxList[0].language === 'CN' ? 'EN' : 'CN',
          telephone: this.inputBoxList[0].telephone
        }
      }
      if (this.datetime) {
        query.datetime = this.datetime
      }
      // 判断第一个旅客是否是英文名
      switch (this.inputBoxList[0].language) {
        case 'EN':
          query.contact.name = this.inputBoxList[0].first_name
          break
        case 'CN':
          query.contact.first_name = this.inputBoxList[0].first_name
          query.contact.last_name = this.inputBoxList[0].last_name
          break
      }
      // }
      // 循环输入ticketEntity,
      this.productTicket.ubr_product.forEach((item) => {
        const ticketEntityItem = {
          code: item.code,
          guest: []
        }
        query.ticketEntity.push(ticketEntityItem)
      })
      // 循环输入guest
      this.inputBoxList.forEach((item, index) => {
        const guestItem = {
          id_type: item.id_type,
          id_no: item.id_no,
          name_type: item.language === 'CN' ? 'EN' : 'CN'
        }
        switch (item.language) {
          case 'EN':
            guestItem.name = item.first_name
            break
          case 'CN':
            guestItem.first_name = item.first_name
            guestItem.last_name = item.last_name
            break
        }
        if (index === 0) {
          guestItem.telephone = this.inputBoxList[0].telephone
        }
        query.ticketEntity.forEach((value, valueIndex, array) => {
          if (item.code === value.code) {
            array[valueIndex].guest.push(guestItem)
          }
        })
        this.passengerList.push(guestItem)
        //
      })
      console.log(query)
      ticketOrder(query).then((res) => {
        if (res.data.code === 200) {
          query.price = this.productTicket.price
          query.code_name = this.productTicket.name
          // 判断是否是单日票
          if (this.productTicket.ubr_product_category === 'SINGLE') {
            query.dateTimeDisplay = true
          } else {
            query.dateTimeDisplay = false
          }
          // 判断是否是套票票
          if (this.productTicket.product_category_display === 'SINGLE') {
            query.categoryDisplay = true
          } else {
            query.categoryDisplay = false
          }
          // 传递套票每种票至少数量
          query.baseNumber = this.baseNumber
          // 传递正常数据输入框数据
          query.passengerList = this.passengerList
          query.uid = this.uid
          uni.redirectTo({
            url: `/pages/payment/payment?query=${JSON.stringify(
              query
            )}&orderUid=${res.data.data.orderUid}`
          })
        } else {
          showToast('创建订单失败')
          this.datetime = this.datetime.slice(0, 10)
        }
      })
    },
    getWeekDay() {
      var today = new Date()
      var dateArr = []
      for (var i = 0; i < 8; i++) {
        var newDate = new Date(today.getTime() + i * 1000 * 60 * 60 * 24)
        var year = newDate.getFullYear()
        var month =
          parseInt(newDate.getMonth()) + 1 > 9
            ? parseInt(newDate.getMonth()) + 1
            : '0' + (parseInt(newDate.getMonth()) + 1)
        var day =
          newDate.getDate() > 9 ? newDate.getDate() : '0' + newDate.getDate()
        var fullDate = `${year}-${month}-${day}`
        dateArr.push({ date: fullDate, ticketBeing: false })
      }
      return dateArr
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  width: 750rpx;
  min-height: calc(100vh - 30rpx);
  background-color: #f5f5f5;
  font-size: 28rpx;
  padding-top: 30rpx;
  color: #000000;
}
.content-card-fa {
  padding-bottom: 140rpx;
}
.content-card-fa-ios {
  padding-bottom: 206rpx;
}
// 主体卡片区域
.content-card {
  width: 710rpx;
  margin-left: 20rpx;
  background-color: #ffffff;
  box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.1);
  border-radius: 8rpx;
  padding-top: 32rpx;
  padding-bottom: 40rpx;
}
.card-commodity-name {
  font-size: 36rpx;
  font-weight: 800;
  color: #000000;
  text-align: left;
  margin-left: 30rpx;
}
/* 购买数量 */
.card-purchase-quantity {
  margin-top: 24rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
  display: flex;
  justify-content: space-between;
}
.card-purchase-quantity-left {
  margin-top: 6rpx;
}
.card-purchase-quantity-right {
  width: 176rpx;
  height: 48rpx;
  border: 2rpx solid #cccccc;
  display: flex;
  text-align: center;
}
.card-purchase-quantity-right-reduce {
  width: 48rpx;
  height: 48rpx;
  border-right: 2rpx solid #cccccc;
}
.reduce-rectangle {
  width: 20rpx;
  height: 4rpx;
  background-color: #9b9b9b;
  text-align: left;
  margin-left: 16rpx;
  margin-top: 24rpx;
}
.reduce-rectangle-rotate {
  position: absolute;
  width: 20rpx;
  height: 4rpx;
  background-color: #9b9b9b;
  text-align: left;
  left: 16rpx;
  top: 24rpx;
  transform: rotate(90deg);
}
.card-purchase-quantity-right-number {
  height: 48rpx;
  width: 76rpx;
  line-height: 48rpx;
}
.card-purchase-quantity-right-add {
  position: relative;
  width: 48rpx;
  height: 48rpx;
  border-left: 2rpx solid #cccccc;
}
</style>
